<template>
  <div class="bond">
    <input
      class="input"
      v-model="keywords"
      type="text"
      placeholder="请输入您要搜索的羁绊名"
      @input="handleSearchInput"
    />

    <!-- 羁绊列表 -->
    <div class="list">
      <div 
        class="item" 
        v-for="item in bonds"
        :key="item.id"
      >
        <!-- 羁绊名称和图标 -->
        <div class="bond-info">
          <img 
            v-if="item.img" 
            :src="getImageUrl(item.img)" 
            :alt="item.name" 
            class="bond-icon" 
            @error="handleImageError" 
          />
          <img 
            v-else 
            src="../assets/default_bond.png" 
            :alt="item.name" 
            class="bond-icon" 
          />
          <div class="name">{{ item.name }}</div>
        </div>

        <!-- 相关英雄信息 -->
        <div class="related-heros">
          <template v-if="relatedHerosMap[item.id] && relatedHerosMap[item.id].length > 0">
            <div 
              v-for="(hero, index) in relatedHerosMap[item.id].slice(0, 2)" 
              :key="hero.id" 
              class="hero-item"
            >
              <img 
                :src="getImageUrl(hero.heroDetail?.img)" 
                :alt="hero.heroDetail?.name" 
                class="hero-icon"
                @error="handleImageError"
              />
              <div class="hero-name">{{ hero.heroDetail?.name }}</div>
            </div>
          </template>
          <div v-else class="loading-hero">
            加载中...
          </div>
        </div>

        <!-- 更多按钮 -->
        <div class="more-btn" @click="goToBondDetail(item.id)">
          更多 >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import { useRouter } from "vue-router";
import request from '@/utils/request'

const router = useRouter();

const state = reactive({
  bonds: [],
  keywords: "",
  loading: true
});

// 存储羁绊相关英雄的映射
const relatedHerosMap = ref({});

// 图片URL处理函数
const getImageUrl = (imgPath) => {
  if (!imgPath) return '';
  if (imgPath.startsWith('http://') || imgPath.startsWith('https://')) {
    return imgPath;
  }
  return `http://localhost:8080${imgPath}`;
};

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.src = require('../assets/default_hero.png');
};

// 获取所有羁绊
const fetchBonds = async () => {
  try {
    state.loading = true;
    const response = await request({
      url: '/bond',
      method: 'get'
    });
    state.bonds = response.data || response;
    await fetchAllRelatedHeros(state.bonds);
  } catch (error) {
    console.error('获取羁绊列表失败:', error);
  } finally {
    state.loading = false;
  }
};

// 获取所有羁绊的相关英雄信息
const fetchAllRelatedHeros = async (bonds) => {
  try {
    const allRelations = await request({
      url: `/heros-bond/details`,
      method: 'get'
    });
    
    const map = {};
    bonds.forEach(bond => {
      const relations = allRelations.data || allRelations;
      map[bond.id] = relations.filter(item => 
        item.bondDetail && item.bondDetail.id === bond.id
      );
    });
    
    relatedHerosMap.value = map;
  } catch (error) {
    console.error('获取相关英雄失败:', error);
  }
};

// 搜索羁绊
const searchBonds = async () => {
  if (!state.keywords.trim()) {
    await fetchBonds();
    return;
  }
  
  try {
    const response = await request({
      url: '/bond/search',
      method: 'get',
      params: { keyword: state.keywords.trim() }
    });
    state.bonds = response.data || response;
    await fetchAllRelatedHeros(state.bonds);
  } catch (error) {
    console.error('搜索羁绊失败:', error);
  }
};

// 防抖搜索处理
let searchTimer = null;
const handleSearchInput = () => {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(() => {
    searchBonds();
  }, 300);
};

// 跳转到羁绊详情页
const goToBondDetail = (id) => {
  router.push({ path: '/bondetail', query: { id: id } });
};

onMounted(() => {
  fetchBonds();
});

const { bonds, keywords } = toRefs(state);
</script>

<style lang="less" scoped>
.bond {
  position: relative;
  min-height: 100vh;
  padding: 20px;
  
  &::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: url('../assets/heard(2).png');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    background-attachment: fixed;
    opacity: 0.3;
    z-index: -1;
  }
  
  .input {
    height: 40px;
    width: 250px;
    padding: 0 15px;
    border: 2px solid #00a383;
    border-radius: 20px;
    font-size: 16px;
    margin-bottom: 20px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(5px);
  }

  .list {
    display: flex;
    flex-direction: column;
    gap: 10px;
    width: 100%;

    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 15px;
      background: rgba(0, 0, 0, 0.3);
      border-radius: 8px;
      transition: background 0.3s;
      width: 100%;

      &:hover {
        background: rgba(0, 163, 131, 0.2);
      }

      .bond-info {
        display: flex;
        align-items: center;
        flex: 1;
        min-width: 200px;
        max-width: 300px;

        .bond-icon {
          width: 50px;
          height: 50px;
          object-fit: contain;
          border: 2px solid #00a383;
          border-radius: 5px;
          margin-right: 15px;
        }

        .name {
          font-size: 18px;
          color: white;
          font-weight: bold;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .related-heros {
        display: flex;
        gap: 15px;
        margin: 0 15px;
        min-width: 150px;

        .hero-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          gap: 5px;
          min-width: 60px;

          .hero-icon {
            width: 40px;
            height: 40px;
            border-radius: 5px;
            border: 1px solid #00a383;
            object-fit: cover;
            background: rgba(255, 255, 255, 0.1);
          }

          .hero-name {
            font-size: 12px;
            color: #ccc;
            text-align: center;
            max-width: 60px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }

        .loading-hero {
          color: #999;
          font-size: 14px;
          font-style: italic;
        }
      }

      .more-btn {
        color: #00a383;
        cursor: pointer;
        padding: 5px 10px;
        border-radius: 4px;
        transition: all 0.3s;
        white-space: nowrap;

        &:hover {
          background: rgba(0, 163, 131, 0.2);
          transform: translateX(3px);
        }
      }
    }
  }
}
</style>
